package com.heima.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import com.heima.media.dto.LoginDto;
import com.heima.media.entity.WmUser;
import com.heima.media.mapper.WmUserMapper;
import com.heima.media.service.IWmUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;

/**
 * <p>
 * 自媒体用户信息表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-04-11
 */
@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements IWmUserService {

    @Override
    public ResponseResult saveWmUser(WmUser user) {

        //参数校验
        if (user == null || user.getApUserId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 新增自媒体用户
        // 判断当前的用户是否已经创建了自媒体用户,可以根据用户注册表ap_user_id 来判断
        // 根据ap_user_id 查询
        LambdaQueryWrapper<WmUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmUser::getApUserId, user.getApUserId());
        WmUser one = this.getOne(queryWrapper);
        // 如果有,直接返回用户信息
        if (one != null) {
            return ResponseResult.okResult(one);
        }
        // 没有的话,创建新的用户来返回
        user.setCreatedTime(new Date());
        this.save(user);
        return ResponseResult.okResult(user);

    }


    @Override
    public ResponseResult login(LoginDto dto) {

        //校验参数
        if (dto == null || dto.getName() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //根据用户名查找用户
        LambdaQueryWrapper<WmUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmUser::getName, dto.getName());
        WmUser one = this.getOne(queryWrapper);
        if (one == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }
        //对比密码
        String pwd = dto.getPassword() + one.getSalt();
        //md5加密
        String md5 = DigestUtils.md5DigestAsHex(pwd.getBytes());
        if (!md5.equals(one.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //密码一致
        //生成token
        HashMap<String, Object> userInfo = new HashMap<>();
        userInfo.put("userId", one.getId());
        String token = AppJwtUtil.getToken(userInfo);

        //返回前端数据，排除敏感字段
        HashMap map = new HashMap();
        WmUser wmUser = new WmUser();
        wmUser.setId(one.getId());
        map.put("user", wmUser);
        map.put("token", token);
        return ResponseResult.okResult(map);
    }



}
